<?php

namespace App\Services;

use App\Models\GameTag;
use App\Models\GameTagRelation;
use common\enum\MasterLogEnum;
use common\utils\SysCode;
use Illuminate\Support\Facades\DB;

class GameTagService
{
    const PID_ZERO = 0;

    public static function getTagList($gameType)
    {
        $tagList = GameTag::from("game_tag as gt")
            ->leftJoin('game_tag_relation as gtr', 'gt.id', '=', 'gtr.tag_id')
            ->select([
                'gt.id',
                'gt.pid',
                'gt.name',
                'gt.game_type',
                'gt.is_default',
                DB::raw('COUNT(gtr.game_id) as num')
            ])
            ->where(['gt.game_type' => $gameType])
            ->groupBy('id')->get()->toArray();
        $ret = [];
        foreach ($tagList as $t) {
            if ($t['pid'] == 0) {
                unset($t['pid']);
                $t['child'] = [];
                $ret[$t['id']] = $t;
            } else {
                $ret[$t['pid']]['child'][] = $t;
                $ret[$t['pid']]['num'] += $t['num'];
            }
        }
        return array_values($ret);
    }

    public static function addTag($name, $pid, $gameType)
    {
        if (!is_int($pid)) {
            error_exit(SysCode::INVALID_ARGUMENT);
        }
        $tag = new GameTag(['name' => $name, 'pid' => $pid, 'game_type' => $gameType]);
        $res = $tag->save();
        if ($res) {
            if ($pid === self::PID_ZERO) {
                $remark = str_replace(['{:title}'], [$name], MasterLogEnum::REMARK['game_tag_add']);
            } else {
                $gameTag = GameTag::where(['id' => $pid])->first();
                $remark = str_replace(['{:title}', '{:sub_title}'], [$gameTag['name'], $name], MasterLogEnum::REMARK['game_tag_add_sub']);
            }
            MasterLogService::writeMasterLog(MasterLogEnum::GAME_LABEL_ADD, MasterLogEnum::SUCCESS, $remark);
        }
        return $res;
    }

    public static function delTag($id)
    {
        $gameTag = GameTag::where(['id' => $id])->first();
        if (empty($gameTag)){
            error_exit(SysCode::INVALID_ARGUMENT, '标签不存在');
        }
        // tag 下有关联游戏，不给删
        if (GameTagRelation::where(['tag_id' => $id])->count() > 0) {
            return error_exit(SysCode::GAME_TAG_DELETE_ERROR);
        }
        // tag 下有子tag，不给删
        if (GameTag::where(['pid' => $id])->count() > 0) {
            return error_exit(SysCode::GAME_TAG_DELETE_ERROR);
        }
        // 只能删除非默认的标签
        $result = GameTag::where(['id' => $id, 'is_default' => false])->delete();
        //删除标签写入日志
        if ($result) {
            if ($gameTag['pid'] === self::PID_ZERO) {
                $remark = str_replace(['{:title}'], [$gameTag['name']], MasterLogEnum::REMARK['game_tag_del']);
            } else {
                $name   = GameTag::where(['id' => $gameTag['pid']])->value('name');
                $remark = str_replace(['{:title}', '{:sub_title}'], [$name, $gameTag['name']], MasterLogEnum::REMARK['game_tag_del_sub']);
            }
            MasterLogService::writeMasterLog(MasterLogEnum::GAME_LABEL_DEL, MasterLogEnum::SUCCESS, $remark);
        }
        return $result;
    }

    public static function updateTag($id, $name)
    {
        return GameTag::where(['id' => $id])->update(['name' => $name]);
    }
}
